package com.chehejia.devmng.platform.manager.impl;


import com.chehejia.devmng.platform.manager.LaPlanManager;
import com.chehejia.devmng.platform.mapstruct.LaPlanCopier;
import com.chehejia.devmng.platform.model.allot.AllotLongStock;
import com.chehejia.devmng.platform.model.allot.LaPlanResultVo;
import com.chehejia.devmng.platform.model.allot.LaPlanTo;
import com.chehejia.devmng.platform.service.CvLaPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 *  * @Description: 长线调配
 *  * @author: 王永坤
 *  * @Date: 2018/12/14 9:26
 *  
 */
@Slf4j
@Service
public class LaPlanManagerImpl implements LaPlanManager {
    @Autowired
    private CvLaPlanService laPlanService;
    @Autowired
    private LaPlanCopier laPlanCopier;

    @Override
    public List<LaPlanResultVo> queryListByYearAndSpu(int year, String spuCode) {
        List<LaPlanResultVo> resultModels = new ArrayList<>();

        List<LaPlanTo> laPlanTos = laPlanCopier.to(laPlanService.queryListByYearAndSpu(year, spuCode));

        // itemType
        List<Integer> itemTypeList = laPlanTos.stream().map(LaPlanTo::getItemType).sorted().distinct().collect(Collectors.toList());

        //vdc 分组
        Map<Integer, List<LaPlanTo>> typeListMap = laPlanTos.stream().collect(Collectors.groupingBy(LaPlanTo::getItemType));
        for (Integer key : itemTypeList) {
            LaPlanResultVo vo = new LaPlanResultVo();
            // 对 他的结果进行。按照vdc 分组。 之后，在安装 weekseq 排序。
            Map<String, List<LaPlanTo>> vdcGroupListMap = typeListMap.get(key).stream().collect(Collectors.groupingBy(LaPlanTo::getVdcCode));
            List<AllotLongStock> rows = new LinkedList<>();
            for (String vdc : vdcGroupListMap.keySet()) {
                AllotLongStock stock = new AllotLongStock();
                List<LaPlanTo> planTos = vdcGroupListMap.get(vdc).stream().sorted(Comparator.comparing(LaPlanTo::getWeekSeq)).collect(Collectors.toList());
                // 计划量
                List<Integer> planCounts = planTos.stream().peek(m -> {
                    stock.setVdcCode(m.getVdcCode());
                    stock.setVdcName(m.getVdcName());
                }).map(LaPlanTo::getPlanCount).collect(Collectors.toList());
                stock.setWeekPlanCount(planCounts);
                rows.add(stock);
            }
            vo.setRows(rows);
            vo.setItemType(key);
            resultModels.add(vo);
        }
        return  resultModels;
    }

    @Override
    public boolean create(LaPlanTo laPlanTo) {
        return  laPlanService.save(laPlanCopier.from(laPlanTo));
    }

}
